package com.ruoyi.manage.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.gson.Gson;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;

public class SmsUtil {

    private static final Logger logger = LoggerFactory.getLogger("file_error");

    /**
     * 短信主账号AccessKey的ID
     */
    @Value(value = "${sms.accessKeyId}")
    private static String ACCESS_KEY_ID;
    /**
     * 短信主账号的密钥
     */
    @Value(value = "${sms.accessKeySecret}")
    private static String ACCESS_KEY_SECRET;

    /**
     * @param phonenumber   需要发送验证码的业主手机号
     * @param signName      短信前面名称，在控制台签名管理页面签名名称一列查看，可存入字典表以防以后修改
     * @param templateCode  短信模板ID。请在控制台模板管理页面模板CODE一列查看，可存入字典表以防以后修改
     * @param templateParam 短信模板变量对应的实际值，也就是短信验证码
     * @return
     */
    @Log(title = "短信发送异常", businessType = BusinessType.INSERT)
    public static void sendSms(String phonenumber, String signName, String templateCode, Map<String,String> templateParam) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        //
        request.setDomain("dysmsapi.aliyuncs.com");
        //
        request.setVersion("2017-05-25");
        // 系统规定参数。取值：SendSms
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        // 接收短信的手机号码
        request.putQueryParameter("PhoneNumbers", phonenumber);
        // 短信签名名称。请在控制台签名管理页面签名名称一列查看
        request.putQueryParameter("SignName", signName);
        // 短信模板ID。请在控制台模板管理页面模板CODE一列查看
        request.putQueryParameter("TemplateCode", templateCode);
        // 短信模板变量对应的实际值，JSON格式
        Gson gson = new Gson();
        request.putQueryParameter("TemplateParam", gson.toJson(templateParam));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            logger.error("短信服务端出错==>", e);
            throw new BusinessException("短信服务端出错");
        } catch (ClientException e) {
            logger.error("短信客户端出错==>", e);
            throw new BusinessException("短信客户端出错");
        }
    }
}
